package www.openteam.com.ui.policy;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.PayableApprovalAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.ApprovalStatu;
import www.openteam.com.bean.PayableApproval;
import www.openteam.com.contract.policy.PayableApprovalContract;
import www.openteam.com.presenter.policy.PayableApprovalPresenter;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * Created by hyd on 2017/1/15.
 * 应付款审批
 */

public class PayableApprovalFragment
        extends mBaseFragment<PayableApprovalPresenter>
        implements PayableApprovalContract.PayableApprovalView {

    View view;
    private ArrayList<PayableApproval.DataEntity> PayableApprovals;
    private ArrayList<PayableApproval.DataEntity> approvals;
    private static int pageSize = 0;
    private final String TAG = PayableApprovalFragment.class.getSimpleName();
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private PayableApprovalAdapter payableApprovalAdapter = null;
    Throwable throwable = null;
    public int changePosition = 0;
    int approval = 0;


    @Bind(R.id.ed_1)
    EditText ed_1;
    @Bind(R.id.ed_3)
    EditText ed_3;
    @Bind(R.id.ed_4)
    EditText ed_4;
    @Bind(R.id.ed_2)
    Spinner ed_2;
    @Bind(R.id.query_btn)
    Button query_btn;
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.tv_3)
    TextView tv_3;
    @Bind(R.id.tv_4)
    TextView tv_4;
    @Bind(R.id.btn1)
    Button btn1;
    @Bind(R.id.btn2)
    Button btn2;
    @Bind(R.id.btn3)
    Button btn3;

    @Bind(R.id.card)
    CardView card;
    @Bind(R.id.tv_title)
    TextView tv_5;

    int j = -1;
    private boolean chk;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
        chk = mySetting.getBoolean("chk", false);
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        tv_3.setText(detail[2]);
        tv_4.setText(detail[3]);
        initSRView(view);
        ed_2.setSelection(0);
        mRecyclerView.addOnScrollListener(mOnScrollListener);

    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initView() {
        tv_5.setMovementMethod(ScrollingMovementMethod.getInstance());
        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        int current_day = c.get(Calendar.DAY_OF_MONTH);
        int current_month = c.get(Calendar.MONTH);
        int current_year = c.get(Calendar.YEAR);
        c.set(current_year, current_month, current_day);
        ed_3.setText(df.format(c.getTime()));
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一周内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
                c.add(Calendar.DATE, -7);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一月内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH) - 1;
                int current_year = c.get(Calendar.YEAR);
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//一年内
                Calendar c = Calendar.getInstance();
                int current_day = c.get(Calendar.DAY_OF_MONTH);
                int current_month = c.get(Calendar.MONTH);
                int current_year = c.get(Calendar.YEAR) - 1;
                c.set(current_year, current_month, current_day);
//                ed_3.setText(df.format(c.getTime()));
//                c.add(Calendar.DATE, 0);
                ed_4.setText(df.format(c.getTime()));
            }
        });

        query_btn.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                createProgressDialog("正在查询,请稍后..");
                if (payableApprovalAdapter == null) {
                    PayableApprovals = new ArrayList<PayableApproval.DataEntity>();
                    approvals = new ArrayList<PayableApproval.DataEntity>();
                    mPresenter.queryPayableApproval(getVendno(), getStartTime(), getEndTime(),
                            getOrderState(), getStype(), getMoreCom(), pageSize);
                    tv_5.setText("");
                    j=-1;
                } else {
                    payableApprovalAdapter.deleteItems(PayableApprovals);
                    mRecyclerView.removeAllViews();
                    approvals.clear();
                    throwable = null;
                    i = 0;
                    PayableApprovals.clear();
                    onRefresh();
                }
            }
        });
    }

    @Override
    protected void otherViewClick(View view) {
        ed_4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectCalendar();
            }
        });
        ed_3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectEndCalendar();
            }
        });
    }

    @Override
    protected PayableApprovalPresenter loadPresenter() {
        return new PayableApprovalPresenter();
    }

    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!getVendno().isEmpty() || getStartTime() != 0 || getEndTime() != 0)) {
            Log.d(TAG, "onRefresh: " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            PayableApprovals.clear();
            payableApprovalAdapter = null;
            approvals.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryPayableApproval(getVendno(), getStartTime(), getEndTime(), getOrderState(), getStype(), getMoreCom(), 0);
            throwable = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
            tv_5.setText("");
            j=-1;
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getVendno().isEmpty() || getStartTime() != 0 || getEndTime() != 0)) {
            mRecyclerView.removeAllViews();
            payableApprovalAdapter = null;
            PayableApprovals.clear();
            approvals.clear();
            mPresenter.queryPayableApproval(getVendno(), getStartTime(), getEndTime(), getOrderState(), getStype(), getMoreCom(), 0);
            mSwipeRefresh.setRefreshing(false);
            tv_5.setText("");
            j=-1;
        }
    }

    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                i++;
            }
            i++;
            if (throwable == null && (PayableApprovals.size() % 10 == 0)) {
                PayableApprovals = new ArrayList<PayableApproval.DataEntity>();
                mPresenter.queryPayableApproval(getVendno(), getStartTime(), getEndTime(),
                        getOrderState(), getStype(), getMoreCom(), i);
                tv_5.setText("");
                j=-1;
                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (PayableApprovals.size() % 10 != 0)) {
                mPresenter.queryPayableApproval(getVendno(), getStartTime(), getEndTime(), getOrderState(), getStype(), getMoreCom(), 0);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
                tv_5.setText("");
                j=-1;
            } else if (throwable != null) {
                i = 0;
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            }

        }
    };

    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryPayableApproval(getVendno(), getStartTime(), getEndTime(), getOrderState(), getStype(), getMoreCom(), i);
            tv_5.setText("");
            j=-1;
        }
    };

    @Override
    public String getVendno() {
        return ed_1.getText().toString();
    }

    @Override
    public long getStartTime() {
        if (!ed_4.getText().toString().isEmpty()) {
            startMilli = changeMilli(ed_4.getText().toString());
        }
        return startMilli;
    }

    @Override
    public long getEndTime() {
        if (!ed_3.getText().toString().isEmpty()) {
            endMilli = changeMilli(ed_3.getText().toString());
        }
        return endMilli;
    }

    @Override
    public String getStype() {
        String stype = mySetting.getString("rCode", "");
        Log.d(TAG, "getStype: " + stype);
        return stype;
    }

    @Override
    public String getMoreCom() {
        String moreCom = mySetting.getString("rMoreCom", "");
//        Log.d(TAG, "getMoreCom: "+moreCom);
        return moreCom;
    }

    @Override
    public int getOrderState() {
        return ed_2.getSelectedItemPosition();
    }


    @Override
    public void queryPASuccess(List<PayableApproval.DataEntity> data) {
        mProgressDialog.dismiss();
        j++;
        for (PayableApproval.DataEntity dev : data) {
            PayableApprovals.add(dev);
            approvals.add(dev);
        }
        setpayableApprovalAdapter();
        card.setVisibility(View.VISIBLE);
        if (j==0){
            PayableApproval.DataEntity item = data.get(0);
            String custName = "";
            if (!item.getVendSName().equals(null)){
                custName =item.getVendSName();
            }else{
                custName=item.getVendname();
            }
            BigDecimal tolMoney = new BigDecimal(item.getTolMoney());
            tv_5.setText(
                    "编号:" + item.getRownumber()+
                            "\n" + "应收款单号:" + item.getRdsno()
                        +"\n" + "客户编号:" + item.getVendno()
                        + "\n" + "客户名称:" + custName
                        + "\n" + "付款方式:" + item.getPayName()
                        + "\n" + "金额:" + item.getTolMoney()+"("+item.getMoneyName()+")"
                + "\n对账日期" +item.getAccntdate()+ "\n" + "状态:" + item.getStatusn()
            );
//            setBtn_audting(item,0);
        }
        payableApprovalAdapter.setOnLineClickListener(new PayableApprovalAdapter.OnLineClickListener() {
            @Override
            public void onClick(PayableApproval.DataEntity item, int postion) {
                String custName = "";
                if (!item.getVendSName().equals(null)){
                    custName =item.getVendSName();
                }else{
                    custName=item.getVendname();
                }
                BigDecimal tolMoney = new BigDecimal(item.getTolMoney());
                tv_5.setText(
                        "编号:" + item.getRownumber()+
                                "\n" + "应收款单号:" + item.getRdsno()
                                +"\n" + "客户编号:" + item.getVendno()
                                + "\n" + "客户名称:" + custName
                                + "\n" + "付款方式:" + item.getPayName()
                                + "\n" + "金额:" + item.getTolMoney()+"("+item.getMoneyName()+")"
                                + "\n对账日期" +item.getAccntdate()+ "\n" + "状态:" + item.getStatusn()
                );
//                setBtn_audting(item,postion);
            }
        });
    }
    public void setBtn_audting(final PayableApproval.DataEntity item,final int postion) {
//        if (chk) {
//            btn_audting.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    createProgressDialog("正在审核,请稍候..");
//                    if (item.getStatusn().equals("已审核")) {
//                        changePosition = postion;
//                        mPresenter.unapprovalStatu(item.getId());
//                    } else if (item.getStatusn().equals("未审核")) {
//                        changePosition = postion;
//                        mPresenter.unapprovalStatu(item.getId());
//                    } else {
//                        ToastUtil.showToast(getActivity(), "不可逆操作");
//                    }
//                }
//            });
//        } else {
//            ToastUtil.showToast(getActivity(), "暂时没有取得权限");
//        }
    }

    private void setpayableApprovalAdapter() {
        if (payableApprovalAdapter == null) {
            payableApprovalAdapter = new PayableApprovalAdapter(getActivity());
            payableApprovalAdapter.addItems(PayableApprovals);
            payableApprovalAdapter.addContext(getActivity());
            payableApprovalAdapter.registerAdapterDataObserver(adapterDataObserver);
            if (chk) {
                payableApprovalAdapter.buttonSetOnclick(new PayableApprovalAdapter.ButtonInterfacet() {

                    @Override
                    public void onclick(View view, int position) {
                        createProgressDialog("正在审核,请稍候..");
                        if (approvals.get(position).getStatusn().equals("")) {
                            changePosition = position;
                            mPresenter.unapprovalStatu(approvals.get(position).getId());
                        } else if (approvals.get(position).getStatusn().equals("未审核")) {
                            changePosition = position;
                            mPresenter.approvalStatu(approvals.get(position).getId());
                        } else {
                            ToastUtil.showToast(getActivity(), "不可逆操作");
                        }

                    }
                });
            } else {
                ToastUtil.showToast(getActivity(), "暂时没有取得权限");
            }
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(payableApprovalAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        } else {
            Log.d(TAG, "setNewAdapter: 2");
            mFooterRecyclerViewAapter.notifyDataSetChanged();
            payableApprovalAdapter.addItems(PayableApprovals);
            if (chk) {
                payableApprovalAdapter.buttonSetOnclick(new PayableApprovalAdapter.ButtonInterfacet() {

                    @Override
                    public void onclick(View view, int position) {
                        if (approvals.get(position).getStatusn().equals("已审核")) {
                            changePosition = position;
                            mPresenter.unapprovalStatu(approvals.get(position).getId());
                        } else if (approvals.get(position).getStatusn().equals("未审核")) {
                            changePosition = position;
                            mPresenter.approvalStatu(approvals.get(position).getId());
                        } else {
                            ToastUtil.showToast(getActivity(), "不可逆操作");
                        }

                    }
                });
            } else {
                ToastUtil.showToast(getActivity(), "暂时没有取得权限");
            }
            RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        }
    }

    @Override
    public void queryPAFail(String failMsg) {
        this.throwable = new Throwable();
        mProgressDialog.dismiss();
        if (failMsg.toString().equals("暂无合适的数据")) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
            ToastUtil.showToast(getActivity(), "暂无匹配数据");
        } else {
            Log.d(TAG, "hideProgress:  esle ");
            RecyclerViewStateUtils.setFooterViewState(getActivity(), this.mRecyclerView, REQUEST_COUNT, LoadingFooter.State.NetWorkError, this.mFooterClick);
            ToastUtil.showToast(getActivity(), "网络连接有误");
        }
    }

    @Override
    public void approvalPASuccess(ApprovalStatu aprovalStatu) {
        approval = 0;
        mProgressDialog.dismiss();
//        onRefresh();
        payableApprovalAdapter.notifyItemChanged(changePosition, new Object());
    }

    @Override
    public void approvalPAFail(String failMsg) {
        mProgressDialog.dismiss();
        ToastUtil.showToast(getContext(), "审核失败");
    }

    RecyclerView.AdapterDataObserver adapterDataObserver = new RecyclerView.AdapterDataObserver() {
        public void onItemRangeChanged(int positionStart, int itemCount) {
            if (approval == 0) {
                payableApprovalAdapter.changeData(changePosition, "已审核");
            } else {
                payableApprovalAdapter.changeData(changePosition, "未审核");
            }
        }
    };

    @Override
    public void unApprovalPASuccess(ApprovalStatu aprovalStatu) {
        mProgressDialog.dismiss();
        approval = 1;
        payableApprovalAdapter.notifyItemChanged(changePosition);
//        onRefresh();
    }

    @Override
    public void unApprovalPAFail(String failMsg) {
        mProgressDialog.dismiss();
        ToastUtil.showToast(getContext(), "反审核失败");
    }


    public void initSRView(View view) {


        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mSwipeRefresh.setOnRefreshListener(this);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);

    }
}
